import { defineStore } from 'pinia'
import { authAPI } from '@/api/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('admin_token') || '',
    userInfo: null
  }),

  getters: {
    isAuthenticated: (state) => !!state.token,
    userName: (state) => state.userInfo?.username || '',
    userRole: (state) => state.userInfo?.role || ''
  },

  actions: {
    // 登录
    async login(credentials) {
      try {
        const response = await authAPI.login(credentials)
        this.token = response.data.token
        localStorage.setItem('admin_token', this.token)

        // 获取用户信息
        await this.getUserInfo()

        return response
      } catch (error) {
        throw error
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const response = await authAPI.getProfile()
        this.userInfo = response.data
        return response
      } catch (error) {
        this.logout()
        throw error
      }
    },

    // 登出
    logout() {
      this.token = ''
      this.userInfo = null
      localStorage.removeItem('admin_token')

      // 调用后端登出接口
      authAPI.logout().catch(() => {
        // 忽略登出接口错误
      })
    },

    // 检查token是否有效
    async checkAuth() {
      if (!this.token) {
        return false
      }

      try {
        await this.getUserInfo()
        return true
      } catch (error) {
        this.logout()
        return false
      }
    }
  }
})